<?php

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
#	FILE:			includes/custom/adminsendnewsletters.php
#	FUNCTION:		Is the custom handler for the Admin Send Newsletter page
#	AUTHOR:			Cameron Morrow
#	CREATED:		02/09/2005
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/*
Notes:
- Select a newsletter to send (a newsletter can be passed via URL from the Browse Newsletters section)
- Select group(s) to send to
- Send


On Sending:
- Get content
- Parse into HTML
- Parse into plain text
- Get Email Addresses
- Create and send email

*/


# Check for submitted
if (@$_POST["newsletterid"]) {

	# ID of newsletter
	$newsletter_id = $_POST["newsletterid"];

	# Check autosending
	$auto_sent = (@$_POST["as"] == "1") ? true : false;

	# Get Email Addresses

	# SQL
	$email_sql = "SELECT u_email FROM " . $PROJECT_DB_TABLES["users"]. " WHERE ";

	# For each POST item
	foreach ($_POST as $post_key => $post_value) {

		# If it is a group
		if (substr($post_key, 0, 3) == "ng_") {

			# Get Group ID
			$newsletter_group = substr($post_key, 3);

			# Add to SQL
			$email_sql .= "u_newsletter_groups LIKE '%," . $newsletter_group . ",%' OR u_newsletter_groups LIKE '" . $newsletter_group . ",%' OR u_newsletter_groups LIKE '%," . $newsletter_group . "' OR u_newsletter_groups = '" . $newsletter_group . "' OR ";
		}
	}

	# Remove last 'OR'
	$email_sql = substr($email_sql, 0, strlen($email_sql) - 3);

	# Extract Email Addresses
	$email_addresses = getRecord($email_sql);
	$email_addresses = extractColumnFromArray($email_addresses, "u_email");

	# Remove dupes
	$email_addresses = array_unique($email_addresses);

	# Get content
	$newsletter_content = getRecord("SELECT n_name, n_content FROM " . $PROJECT_DB_TABLES["newsletters"] . " WHERE n_id = '" . $newsletter_id . "'");
	$newsletter_name = $newsletter_content[0]["n_name"];
	$newsletter_content = $newsletter_content[0]["n_content"];
	
	# Parse as HTML
	$newsletter_content = parseFlashXML($newsletter_content);

	# Create plain-text version by stripping out tags
	$newsletter_plain = preg_replace(
		array("/<[^>]*>/i"),
		array("\n"),
		$newsletter_content);

	# Eliminate excess linebreaks brought in in various phases
	$newsletter_plain = explode("\n", $newsletter_plain);
	$newsletter_plain = implode("[BR]", $newsletter_plain);
	while (strpos($newsletter_plain, "[BR][BR]") !== false) {
		$newsletter_plain = str_replace(array("[BR][BR]"), array("[BR]"), $newsletter_plain);
	}
	$newsletter_plain = str_replace(array("[BR]"), array("\n"), $newsletter_plain);

	# Add footer for plain email
	$newsletter_plain .= "\n----------------------------------------------------------------\nCopyright &copy; Zone 4";

	# Replace <img> src attributes with absolute URLs
	$newsletter_content = preg_replace(
		array("/<img src\=\"\.\.\//i"),
		array("<img src=\"" . $PROJECT_URL),
		$newsletter_content);

	# Find First Image tag and remove it
	$first_image = "";

	# Check if first element in an image
	$first_element_index = strpos($newsletter_content, "elementcontainer");
	$first_element = substr($newsletter_content, $first_element_index + strlen("elementcontainer") + 2);
	$first_element_class_end = strpos($first_element, "container\"");
	$first_element = substr($first_element, 0, $first_element_class_end);
	$first_element = substr($first_element, strrpos($first_element, "\"") + 1);
	$first_element_image = ($first_element == "image");

	# If an image, extract it to use as header
	if ($first_element_image) {

		# Index of first image element
		$image_element_index = strpos($newsletter_content, "<td", $first_element_index);

		# Image area
		$first_image = substr($newsletter_content, $image_element_index);
		$first_image = substr($first_image, 0, strpos($first_image, "</td>") + strlen("</td>"));

		# Remove from the main newsletter content
		$newsletter_content = substr($newsletter_content, 0, $image_element_index) . substr($newsletter_content, $image_element_index + strlen($first_image));

		# Get source
		$first_image = substr($first_image, strpos($first_image, "src=\"") + 5);
		$first_image = substr($first_image, 0, strpos($first_image, "\""));

		# Create header
		$header = "<img src=\"" . $first_image . "\" alt=\"Header\" />";

	} else {

		# Create generic header
		$header = "<h1>Newsletter</h1>";
	}

	# Footer
	$footer = "<p>Copyright Zone 4</p>";

	# Combine
	$newsletter_content = $header . $newsletter_content . $footer;


	# S E N D

	# Create
	$mail = createEmail("editor2@zone4.com.au", "", $newsletter_name);

	# Add Body
	$mail = addEmailBody($mail, $newsletter_content, $newsletter_plain);

	# Send to mailing list
	$success = sendToMailingList($mail, $email_addresses);

	# Feedback
	if ($success === true) {

		addContent("<h2>Newsletter successfully sent</h2><p>The newsletter was sent successfully to all recipients. You can send additional newsletters if you wish.</p>");

		$success = "true";

	} else if ($success === false) {

		addContent("<h2>Newsletter failed to send</h2><p>The newsletter could not be sent to any recipients.</p>");

		$success = "false";

	} else {

		addContent("<h2>Newsletter partially sent</h2><p>The newsletter was successfully sent to some recipients, but not all. Please check the error messages for a list of users who could not be emailed.</p>");
	}

	# Log
	addLog(implode(",", $email_addresses) . "|" . $newsletter_id . "|" . $success, 30);


	# If succeeded
	if ($success !== false) {

		# Get list of current sent times
		$sent_times = getRecord("SELECT n_sent FROM " . $PROJECT_DB_TABLES["newsletters"] . " WHERE n_id = " . $newsletter_id);

		if (count($sent_times) == 1) {

			# Sent times
			$sent_times = $sent_times[0]["n_sent"];

			# Append current time
			if ($sent_times == "") {
				$sent_times = getFullDate();
			} else {
				$sent_times .= "," . getFullDate();
			}

			# Create SQL
			$sql = "UPDATE " . $PROJECT_DB_TABLES["newsletters"] . " SET n_sent = '" . $sent_times . "'";

			# Update AutoSent
			if ($auto_sent) {
				$sql .= ", n_autosent = 1";
			}

			# End SQL
			$sql .= " WHERE n_id = " . $newsletter_id;

			# Execute
			executeSQLQuery($sql, false);
		}
	}


} else {

	# Check if a newsletter was pre-selected
	$selected_newsletter = (@$_GET["nl"]) ? $_GET["nl"] : null;

	# Check if auto-sending
	$auto_sending = (@$_GET["as"]) ? true : false;

	# Get list of Newsletters to send
	$available_newsletters = getRecord("SELECT n_id, n_name, n_autosendgroups FROM " . $PROJECT_DB_TABLES["newsletters"] . " ORDER BY n_created DESC");
	$available_newsletter_names = extractColumnFromArray($available_newsletters, "n_name");
	$available_newsletter_ids = extractColumnFromArray($available_newsletters, "n_id");

	# Get list of groups to send to
	$newsletter_groups = getRecord("SELECT ng_id, ng_name FROM " . $PROJECT_DB_TABLES["newsletter_groups"] . " ORDER BY ng_name ASC");

	# Start
	addContent("<h2>Send Newsletters</h2>" .
		"<form name=\"sendnewsletterform\" id=\"sendnewsletterform\" action=\"" . $PAGE_ID . ".php\" method=\"post\">");

	# If already selected a newsletter...
	if ($selected_newsletter) {

		# Auto-select newsletter
		addContent("<input type=\"hidden\" id=\"newsletterid\" name=\"newsletterid\" value=\"" . $selected_newsletter . "\" />");

		# Auto send
		addContent("<input type=\"hidden\" id=\"as\" name=\"as\" value=\"" . ($auto_sending ? "1" : "0") . "\" />");

		# Get name of selected newsletter
		$selected_name = "";

		# Get list of groups to automatically select
		$selected_groups = array();

		foreach ($available_newsletters as $newsletter) {
			if ($newsletter["n_id"] == $selected_newsletter) {
				if ($newsletter["n_autosendgroups"] != "") {
					$selected_groups = explode(",", $newsletter["n_autosendgroups"]);
				}
				$selected_name = $newsletter["n_name"];
			}
		}

		# Show name
		addContent("<p>Selected newsletter: <strong>" . $selected_name . "</strong></p>");

	} else {

		# Select a newsletter
		addContent("<p>Select a newsletter to send:</p>");

		# Check some newsletters were found
		if (count($available_newsletters) > 0) {
			addContent("<p>" . createSelector("newsletterid", $available_newsletter_names, $available_newsletter_ids, 0) . "</p>");
		} else {
			addContent("<p><em>No newsletters have been created. Please create a newsletter to send.</em></p>");
		}

		# No automatically selected groups
		$selected_groups = array();
	}

	# Select groups to send to
	addContent("<p>Select group(s) to send the newsletter to:</p>");
	foreach ($newsletter_groups as $newsletter_group) {
		
		# Check if checked
		$checked = findInArray($selected_groups, $newsletter_group["ng_id"]) !== false;

		addContent("<p><input type=\"checkbox\" id=\"ng_" . $newsletter_group["ng_id"] . "\" name=\"ng_" . $newsletter_group["ng_id"] . "\"" . ($checked ? " checked=\"checked\"" : "") . " />" . $newsletter_group["ng_name"] . "</p>");
	}

	# End
	addContent("<p><input type=\"submit\" value=\"Send Newsletter\" /></p></form>");

}
?>